// pages/goods/goods.js
import regeneratorRuntime from '../../lib/wxPromise.min.js'
let WxParse = require('../../lib/wxParse/wxParse.js')
let util = require('../../utils/util.js')
import * as API_Goods from '../../api/goods'
import * as API_Members from '../../api/members'
import * as API_Trade from '../../api/trade'
import * as API_Promotions from '../../api/promotions'
import * as API_Common from '../../api/common.js'
import * as API_Distribution from '../../api/distribution.js'
import { Foundation } from '../../ui-utils/index.js'
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 店铺信息
    shopData: {},
    /** 商品信息相关 */
    goods_id: 0,//商品id
    goods: {},//商品详情信息
    param_list: [],//商品参数
    gallery_list: [],//商品轮播图片
    /** 促销相关 */
    promotions: '', // 促销信息
    showPromotion: true,
    prom: '',//积分信息
    groupbuy: '',//团购信息
    seckill: '',//限时信息
    shetuan: '', // 社区团购信息
    assemble: '',//拼团信息
    assembleOrderList: '',//待成团订单
    is_assemble: false,//是否是拼团

    tabIndex: 0,//tab切换
    grade: 0,//好评率
    in_store: true, // 配送地区是否有货状态 默认有货
    cartGoodsCount: 0,//购物车商品数量
    /** 规格相关 */
    showSpecsPopup: false, // 是否显示规格选择弹窗 默认不显示 为false
    selectedSku: '',// 已选sku
    skuId: '', // 路由加载参数中携带的skuId
    pintuanId: '',// 路由加载参数中携带的pintuanId
    from_nav: '', //路由加载参数中携带的from_nav
    buyNum: 1, // 所选商品数量

    hiddenPrice: false,//是否隐藏价格
    canView: false,// 当前商品是否可预览

    /* 收藏相关 */
    collected: false, // 商品是否已被收藏

    scrollHeight: 0, // 滚动高度
    scrollTop: 0, // 滚动距离
    showGoTop: false, // 显示返回顶部按钮
    finished: false, // 是否加载完毕
    showShare: false,//分享
    isShowPoster: false, // 是否显示海报弹窗
    posterImageUrl: '',
    audit_status: ''
  },
  // tab切换
  tabs(e) {
    let index = parseInt(e.currentTarget.dataset.index)
    this.setData({ tabIndex: index })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options) {
      if (options.scene) {
        // 解析第一个值为goods_id;第二个值为share_key
        let _scene = decodeURIComponent(options.scene).split('&');
        options = {
          goods_id: _scene[0]
        };
      };
      // 页面初始化 options为页面跳转所带来的参数
      this.setData({
        goods_id: options.goods_id ? parseInt(options.goods_id) : '',
        skuId: options.sku_id ? parseInt(options.sku_id) : '',
        pintuanId: options.pintuan_id || '',
        from_nav: options.from_nav || '',
        audit_status: wx.getStorageSync('distributor').audit_status
      });
    };
    wx.getSystemInfo({
      success: (res) => {
        this.setData({ scrollHeight: res.windowHeight + 'px' })
      }
    });
    // 获取分享时需要绑定的key
    app.getShareKey('pages/goods/goods', 'shareGoods');
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getPageData();
  },
  // 获取页面数据
  async getPageData() {
    let goods = {}
    try {
      goods = await API_Goods.getGoods(this.data.goods_id)
    } catch (e) {
      wx.showToast({ title: '商品已不存在', icon: 'none' })
    };
    goods.mktprice = goods.mktprice && goods.mktprice > goods.price ? Foundation.formatPrice(goods.mktprice) : 0;
    goods.price = Foundation.formatPrice(goods.price);
    goods.show_tag = goods.is_local === 1;
    this.setData({
      goods: goods,
      grade: goods.grade,
      param_list: goods.param_list,
      gallery_list: goods.gallery_list || [],
      canView: goods.is_auth !== 0 && goods.goods_off === 1,
      selectedSku: ''
    })
    this.getGoodsInfo();
    WxParse.wxParse('goodsDetail', 'html', goods.intro, this)
  },
  // 获取自营标签
  getSelfOperated(e) {
    this.setData({
      shopData: e.detail,
      self_operated: e.detail.self_operated === 1
    });
  },
  // 获取商品活动信息
  getGoodsInfo() {
    //如果商品可以查看
    if (this.data.canView) {
      let pages = getCurrentPages();//获取加载页面
      let currentPage = pages[pages.length - 1];//获取当前页面的对象
      let route = currentPage.route;//获取当前页面路径
      let goods_id = currentPage.options.goods_id;//获取当前路由参数
      let url = route + '/' + goods_id //完整路径
      API_Common.recordView(url) //记录浏览量统计

      //如果存在sku_id 并且带有拼团标识
      if (this.data.skuId && this.data.from_nav === 'assemble') {
        this.setData({ is_assemble: true })
        API_Promotions.getAssembleDetail(this.data.skuId).then(response => {
          response.reduce_moeny = Foundation.formatPrice(response.origin_price - response.sales_price)
          response.sales_price = Foundation.formatPrice(response.sales_price)
          response.origin_price = Foundation.formatPrice(response.origin_price)
          this.setData({ assemble: response })
        })
      } else {
        //获取商品活动内容
        API_Promotions.getGoodsPromotions(this.data.goods_id).then(response => {
          const promotions = response
          let nowtime = parseInt(new Date() / 1000)
          if (promotions && promotions.length) {
            let prom = promotions[0].exchange || ''
            let groupbuy = promotions[0].groupbuy_goods_vo || ''
            let seckill = promotions[0].seckill_goods_vo || ''
            //格式化价格
            if (prom) {
              prom.exchange_money = Foundation.formatPrice(prom.exchange_money)
              prom.goods_price = Foundation.formatPrice(prom.goods_price)
            } else if (groupbuy) {
              groupbuy.price = Foundation.formatPrice(groupbuy.price)
              groupbuy.original_price = Foundation.formatPrice(groupbuy.original_price)
              groupbuy.end_time = promotions[0].end_time - nowtime
            } else if (seckill) {
              seckill.seckill_price = Foundation.formatPrice(seckill.seckill_price)
              seckill.original_price = Foundation.formatPrice(seckill.original_price)
            }
            // 如果有社区团购，隐藏价格
            const shetuan_promotions = promotions.filter(item => item.shetuan_goods_vo);
            let sheTuan = '';
            if (shetuan_promotions[0]) {
              this.setData({ hiddenPrice: true });
              // const _current_shetuan = shetuan_promotions.filter(item => item.sku_id === this.data.skuId);
              const _current_shetuan = shetuan_promotions[0];
              this.setData({
                skuId: _current_shetuan.sku_id
              });
              sheTuan = _current_shetuan.shetuan_goods_vo;
              sheTuan.shetuan_price = Foundation.formatPrice(sheTuan.shetuan_price);
              sheTuan.price = Foundation.formatPrice(sheTuan.price);
              sheTuan.original_price = Foundation.formatPrice(sheTuan.original_price);
            };
            this.setData({
              promotions: promotions,
              prom: prom,
              groupbuy: groupbuy,
              seckill: seckill,
              shetuan: sheTuan
            });
            // 如果有团购，隐藏价格
            if (promotions.filter(item => item.groupbuy_goods_vo)[0]) {
              this.setData({ hiddenPrice: true })
            }
            // 如果有限时抢购，隐藏价格
            if (promotions.filter(item => item.seckill_goods_vo)[0]) {
              this.setData({ hiddenPrice: true })
            }
            // 如果有积分兑换，隐藏价格
            if (promotions.filter(item => item.exchange)[0]) {
              this.setData({ hiddenPrice: true })
            }
          } else {
            if (!promotions || !promotions.length) {
              this.setData({ hiddenPrice: false })
            }
          }
        })
      }
    }
    if (wx.getStorageSync('refresh_token')) {
      //获取收藏状态
      API_Members.getGoodsIsCollect(this.data.goods_id).then(response => {
        this.setData({
          collected: response.message
        })
      })
      //获取购物车数量
      this.getAllCount()
    }
  },
  // 获取购物车数量
  getAllCount() {
    let { city } = app.globalData.locationData;
    API_Trade.getCartCount(city).then(res => {
      this.setData({ cartGoodsCount: res.TOTAL_CART || 0 })
    });
  },
  //配送地区是否有货发生改变
  handleInStockChange(e) {
    const in_store = e.detail
    this.setData({ in_store: in_store })
  },
  // 所选规格发生变化 sku变化
  onSkuChanged(sku) {
    if (this.data.sku_id && this.data.from_nav === 'assemble') {
      this.setData({ is_assemble: true });
      /** 查询获取某个拼团的sku详情 */
      const { sku_id } = sku.detail;
      API_Promotions.getAssembleDetail(sku_id).then(res => {
        this.setData({ assemble: res });
      })
    }
    if (sku.detail) {
      sku.detail.price = Foundation.formatPrice(sku.detail.price)
      this.setData({ selectedSku: sku.detail })
    }
  },
  // 所选规格数量发生变化
  onNumChanged(num) {
    this.setData({ buyNum: num.detail })
  },
  // 去首页
  goHome() {
    wx.switchTab({ url: '/pages/index/index' })
  },
  // 返回上页
  goReturn() {
    wx.navigateBack()
  },
  // 滚动
  scroll(e) {
    if (e.detail.scrollTop > 200) {
      this.setData({ showGoTop: true })
    } else {
      this.setData({ showGoTop: false })
    }
  },
  // 返回顶部
  goTop() {
    this.setData({ scrollTop: 0 })
  },
  // 跳转到购物车
  openCartPage() {
    wx.switchTab({ url: '/pages/cart/cart' })
  },
  // 跳转到店铺
  openSeller(e) {
    let seller_id = e.currentTarget.dataset.seller_id
    wx.navigateTo({
      url: '/pages/shop/shop_id/shop_id?id=' + seller_id
    })
  },
  // 收藏商品
  addCannelCollect() {
    if (!wx.getStorageSync('refresh_token')) {
      wx.showToast({ title: '您还未登录!', image: 'https://localhost/images/icon_error.png' })
      return false
    }
    const { goods_id } = this.data.goods
    if (this.data.collected) {
      API_Members.deleteGoodsCollection(goods_id).then(() => {
        wx.showToast({ title: '取消收藏成功!' })
        this.setData({ collected: false })
      })
    } else {
      API_Members.collectionGoods(goods_id).then(() => {
        wx.showToast({ title: '收藏成功!' })
        this.setData({ collected: true })
      })
    }
  },
  // 分享
  handShare() {
    this.setData({ showShare: true })
  },
  cloneDialog() {
    this.setData({ showShare: false })
  },
  /** 加入购物车 */
  handleAddToCart: util.throttle(function () {
    wx.vibrateShort({});
    if (!this.data.in_store || !this.isLogin()) return
    const { buyNum } = this.data
    const { sku_id } = this.data.selectedSku
    API_Trade.addToCart(sku_id, buyNum, this.getActivityId()).then(response => {
      wx.showToast({ title: '加入购物车成功', icon: 'none' });
      //更新购物车数量
      this.getAllCount();
    });
  }),
  // 登录校验
  isLogin() {
    if (!wx.getStorageSync('refresh_token')) { // 如果没有登录
      wx.showModal({
        title: '提示',
        content: '您还未登录，要现在去登录吗？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({ url: '/pages/auth/login/login' })
          }
        }
      })
      return false
    } else {
      if (!this.data.selectedSku) {
        wx.showToast({
          title: '请选择商品规格！',
          icon: 'none',
          duration: 1500
        })
        this.setData({ showSpecsPopup: true })
        return false
      } else {
        return true
      };
    };
  },
  // 立即购买
  BuyNow: util.throttle(function () {
    wx.vibrateShort({});
    if (!this.data.in_store || !this.isLogin()) return
    const { goods, buyNum } = this.data;
    const { sku_id } = this.data.selectedSku;
    API_Trade.buyNow(sku_id, buyNum, this.getActivityId()).then((response) => {
      this.setData({ showSpecsPopup: false });
      let _url = response.cart_source_type === 'SHETUAN_CART' ? '/pages/shopping/checkout/checkout-group' : '/pages/shopping/checkout/checkout';
      wx.navigateTo({
        url: `${_url}?way=BUY_NOW&&sellerId=${goods.seller_id}`
      });
    })
  }),
  // 拼团买 创建拼团订单
  handleAssembleBuyNow: util.throttle(function () {
    if (!this.data.in_store || !this.isLogin()) return
    const { buyNum } = this.data;
    const { sku_id } = this.data.selectedSku;
    API_Trade.addToAssembleCart(sku_id, buyNum).then((response) => {
      wx.navigateTo({ url: '/pages/shopping/checkout/checkout?from_nav=assemble' })
    })
  }),
  // 参与拼团
  toAssembleBuyNow(e) {
    const order = e.detail
    if (!this.data.in_store || !this.isLogin()) return
    const { buyNum } = this.data;
    const { sku_id } = this.data.selectedSku;
    API_Trade.addToAssembleCart(sku_id, buyNum).then(response => {
      wx.navigateTo({ url: `/pages/shopping/checkout/checkout?order_id=${order.order_id}&from_nav=assemble` })
    })
  },
  // 获取活动id
  getActivityId() {
    const { promotions, shetuan } = this.data
    if (!promotions || !promotions.length) return ''
    let pro
    for (let i = 0; i < promotions.length; i++) {
      let item = promotions[i]
      if (item.exchange || item.groupbuy_goods_do || item.seckill_goods_vo) {
        pro = item
        break
      }
    }
    if (shetuan) {
      shetuan.activity_id = shetuan.shetuan_id
      pro = shetuan
    }
    if (!pro) return ''
    return pro.activity_id
  },

  // 分享查看海报
  createPoster() {
    wx.showLoading({
      title: '海报生成中...',
      icon: 'loading',
      duration: 8000
    });
    let _goodsId = this.data.goods_id;
    let _shareKey = wx.getStorageSync('shareGoods') || '';
    let _opt = _shareKey ? `&${_shareKey}`: '';
    let _params = {
      'page_type': 1, // 1:商品详情；2:微页面；0:无额外数据请求
      'query_id': _goodsId,
      'page_path': 'pages/goods/goods',
      'scene': `${_goodsId}${_opt}`
    };
    // 获取海报需要显示的信息
    API_Goods.getSunCode(_params).then(res => {
      if (res.master_pic && res.master_pic.indexOf('http:') > -1) {
        res.master_pic = `https:${res.master_pic.split('http:')[1]}`;
      };
      if (res.sun_code_url && res.sun_code_url.indexOf('http:') > -1) {
        res.sun_code_url = `https:${res.sun_code_url.split('http:')[1]}`;
      };
      this.createNewImg(res);
    });
  },
  // 将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg(posterData) {
    let { goods_name, selling, master_pic, mktprice, price, sun_code_url } = posterData;
    let that = this;
    let goodsUrl = '';
    let codeUrl = '';
    let _urlArr = [
      {
        url: master_pic,
        type: 1
      },
      {
        url: sun_code_url,
        type: 2
      }
    ];
    for (let urlItem of _urlArr) {
      wx.downloadFile({
        url: urlItem.url,
        success: function (res) {
          if (res.statusCode === 200) {
            const _urlNeed = res.tempFilePath;
            if (urlItem.type === 1) {
              goodsUrl = _urlNeed;
            } else if (urlItem.type === 2) {
              codeUrl = _urlNeed;
            };
            if (goodsUrl && codeUrl) {
              let context = wx.createCanvasContext('canvasPoster');
              context.setFillStyle("#ffffff");
              context.fillRect(0, 0, 340, 450);
              // 商品图
              context.drawImage(goodsUrl, 0, 0, 340, 305);
              // 太阳码
              context.drawImage(codeUrl, 13, 316, 98, 98);
              // 长按识别查看
              context.setFontSize(10),
              context.setFillStyle('#818181');
              context.fillText('长按识别查看', 34, 428, 62);
              // 商品名称
              let textArr = goods_name.split('');
              let temp = '';
              let row = [];
              context.setFontSize(15),
              context.setFillStyle('#000000');
              for (let a = 0; a < textArr.length; a++) {
                if (context.measureText(temp).width < 200) {
                  temp += textArr[a];
                } else {
                  a--; // 这里添加了a-- 是为了防止字符丢失
                  row.push(temp);
                  temp = '';
                };
              };
              row.push(temp);
              //如果数组长度大于2 则截取前两个
              if (row.length > 2) {
                let rowCut = row.slice(0, 2);
                let rowPart = rowCut[1];
                let test = '';
                let empty = [];
                for (let a = 0; a < rowPart.length; a++) {
                  if (context.measureText(test).width < 175) {
                    test += rowPart[a];
                  } else {
                    break;
                  };
                };
                empty.push(test);
                let group = empty[0] + '...'; // 这里只显示两行，超出的用...表示
                rowCut.splice(1, 1, group);
                row = rowCut;
              };
              for (let b = 0; b < row.length; b++) {
                context.fillText(row[b], 120, 335 + b * 18, 195);
              };
              // 商品描述 selling
              context.setFontSize(12),
              context.setFillStyle('#8B8B8B');
              let text = '';
              let emptyText = [];
              selling = selling ? selling : goods_name;
              for (let a = 0; a < selling.length; a++) {
                if (context.measureText(text).width < 195) {
                  text += selling[a];
                } else {
                  break;
                };
              };
              emptyText.push(text);
              let _showWidth = context.measureText(selling).width;
              let groupText = _showWidth < 190 ? selling : emptyText[0] + '...'; // 超出的用...表示
              let groupY = row.length < 2 ? 353 : 371;
              context.fillText(groupText, 120, groupY, 195);
              let priceWidth = 0;
              if (mktprice && mktprice != 'null') {
                // 商品划线价
                context.setFontSize(12),
                context.setFillStyle('#818181');
                priceWidth = context.measureText(`¥${Foundation.formatPrice(price)}`).width;
                context.fillText(`¥${Foundation.formatPrice(mktprice)}`, 120 + priceWidth + 30, 405, 80);
              };

              // 商品价格
              context.font = 'normal bold 18px sans-serif';
              context.setFillStyle('#E83227');
              context.fillText(`¥${Foundation.formatPrice(price)}`, 120, 405, 140);
              if (mktprice && mktprice != 'null') {
                let mktWidth = context.measureText(`¥${Foundation.formatPrice(mktprice)}`).width;
                context.moveTo(146 + priceWidth, 401);
                context.lineTo(136 + priceWidth + mktWidth, 401);
                context.strokeStyle = '#818181';
                context.stroke();
              };
              // 绘图
              context.draw(false, setTimeout(() => {
                wx.canvasToTempFilePath({
                  canvasId: 'canvasPoster',
                  success: function (response) {
                    let tempFilePath = response.tempFilePath;
                    that.setData({
                      posterImageUrl: tempFilePath,
                      isShowPoster: true
                    });
                  },
                  fail: function (err) {
                    console.log(err);
                  },
                  complete: function () {
                    wx.hideLoading()
                  }
                })
              }, 500));
            };
          };
        }
      });
    };
  },
  // 保存到相册
  savePoster() {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.posterImageUrl,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 关闭海报弹层 */
              that.closePoster();
            }
          }, fail: function (error) {
            console.log('保存失败')
          }
        })
      }
    })
  },
  // 关闭海报弹层
  closePoster() {
    this.setData({
      isShowPoster: false
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let _goodsId = this.data.goods_id;
    let _shareKey = wx.getStorageSync('shareGoods') || '';
    let _opt = _shareKey ? `&shareKey=${_shareKey}`: '';
    const _this = this;
    const { goods, showPromotion, seckill, shetuan } = _this.data;
    let _shareTitle = goods.goods_name;
    if (showPromotion) {
      if (seckill) {
        _shareTitle = `${seckill.seckill_price}元秒杀${_shareTitle}`;
      } else if (shetuan) {
        _shareTitle = `${shetuan.shetuan_price}元团购${_shareTitle}`;
      };
    };
    return {
      title: _shareTitle,
      desc: goods.meta_description || goods.goods_name,
      path: `/pages/goods/goods?goods_id=${_goodsId}${_opt}`,
      imageUrl: goods.thumbnail
    }
  }
})
